package com.uci.scheduleshare;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.view.Window;

/**
 * CS 190 Spring 2012
 * SettingsActivity.java
 * The PreferenceActivity for displaying and saving preferences
 * 
 * @author Patrick Hsu, Lauren Ko, Pomi Park
 *
 */
public class SettingsActivity extends PreferenceActivity{
	
	static List<String[]> calendarNames;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		getFragmentManager().beginTransaction().replace(android.R.id.content,
                new PrefsFragment()).commit();
		DBApplication dbApp = (DBApplication)getApplication();
		// Get all the calendar names and id's from the user's Android device
		calendarNames = dbApp.getDbAdapter().getAllCalendarNames();
	}
	
	/**
	 * A class for displaying a PreferenceFragment - a section of the 
	 * PreferenceActivity
	 *
	 */
    public class PrefsFragment extends PreferenceFragment {
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		addPreferencesFromResource(R.xml.preferences);
    		ListPreference lp = (ListPreference) findPreference("default_calendar");
    		
    		// Set all the entries of the ListPreference (calendar names)
    		lp.setEntries(calendarNames.get(0));
    		// Set all the entry values of the ListPreference (calendar ids)
    		lp.setEntryValues(calendarNames.get(1));
    		
    		lp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
				@Override
				public boolean onPreferenceChange(Preference preference, Object newValue) {
					// When a preference is changed, set the value in SharedPreferences and then
					// return it in the intent
					SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
					SharedPreferences.Editor prefsEditor = myPrefs.edit();
					prefsEditor.putString("default_calendar", newValue.toString());
					prefsEditor.commit();
					Intent intent = new Intent();
					intent.putExtra("defaultCalendarID", newValue.toString());
					setResult(Activity.RESULT_OK, intent);
					return true;
				}
			});
    	}
    }

}
